package com.ivory.valley.controller;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.ivory.valley.IvoryUtils;
import com.ivory.valley.common.SignAttr;


@RestController
@RequestMapping("/signconfig")
public class SignController {
	/**
	 * 使用JS-SDK的页面必须先注入配置信息
	 * @param request
	 * @param response
	 * @param url
	 * @return
	 */
	//private static String jsapi_ticket = "kgt8ON7yVITDhtdwci0qeZmljyt-5fFg4idFDNcuTQPzauA9DlbSqtGb9vnBNbx0l8trfwRoy6xuKTnPtfaFmw";
	/* public static void main(String[] args) {
	        String jsapi_ticket = "jsapi_ticket";

	        // 注意 URL 一定要动态获取，不能 hardcode
	        String url = "http://example.com";
	        Map<String, String> ret = sign(jsapi_ticket, url);
	        for (Map.Entry entry : ret.entrySet()) {
	            System.out.println(entry.getKey() + ", " + entry.getValue());
	        }
	    };*/
	    
	    @RequestMapping(value="/sign.dx",method=RequestMethod.POST)
	    public  Map<String, String> sign(HttpServletRequest request,HttpServletResponse response, String url) {
	    	//暂时解决跨域问题 *表示允许所有跨域  这是极不安全的
	    	response.setHeader("Access-Control-Allow-Origin", "*");
	    	IvoryUtils ivoryUtils = new IvoryUtils();
	    	ivoryUtils.checkAccessToken();
	    	ivoryUtils.checkTicket();
	        Map<String, String> ret = new HashMap<String, String>();
	        String nonce_str = create_nonce_str();
	        String timestamp = create_timestamp();
	        String string1;
	        String signature = "";
	        
	        //注意这里参数名必须全部小写，且必须有序
	        string1 = "jsapi_ticket=" + SignAttr.Jsapi_Ticket +
	                  "&noncestr=" + nonce_str +
	                  "&timestamp=" + timestamp +
	                  "&url=" + url;

	        try
	        {
	            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
	            crypt.reset();
	            crypt.update(string1.getBytes("UTF-8"));
	            signature = byteToHex(crypt.digest());
	        }
	        catch (NoSuchAlgorithmException e)
	        {
	            e.printStackTrace();
	        }
	        catch (UnsupportedEncodingException e)
	        {
	            e.printStackTrace();
	        }

	        ret.put("url", url);
	        ret.put("jsapi_ticket", SignAttr.Jsapi_Ticket);
	        ret.put("nonceStr", nonce_str);
	        ret.put("timestamp", timestamp);
	        ret.put("signature", signature);
	        SignAttr.Signature = signature;
	        return ret;
	    }

	    private static String byteToHex(final byte[] hash) {
	        Formatter formatter = new Formatter();
	        for (byte b : hash)
	        {
	            formatter.format("%02x", b);
	        }
	        String result = formatter.toString();
	        formatter.close();
	        return result;
	    }

	    private static String create_nonce_str() {
	        return UUID.randomUUID().toString();
	    }

	    private static String create_timestamp() {
	        return Long.toString(System.currentTimeMillis() / 1000);
	    }
}
